import page
import mwclient
import Queue

class Page_Tracker:
    def __init__(self):
        self.site = mwclient.Site('en.wikipedia.org')

    def find_path(self, start_url, end_url):
        page_cache = {} # dictionary containing {url : page object}
        path_queue = Queue.Queue() # a queue used in the shortest-path algorithm
        start_page = page.Page(start_url)
        print 'hello!'
        start_page.children = self._get_page_children_(start_page)
        path_queue.put(start_page)
        while not path_queue.empty():
            cur = path_queue.get()
            print "look at page: " + cur.url + "\n"
            for child in cur.children:
                #url = child.name.encode('utf-8')
                url = child.name
                if not (url in page_cache):
                    # the page has not been visited yet
                    # so make a new page for it
                    child_page = page.Page(url)
                    # and download the list of children of the child page (as a generator)
                    child_page.children = self._get_page_children_(child_page)
                    # place the child's url in the page_cache so we know we've seen it
                    page_cache[url] = child_page
                    child_page.path_to = cur
                    if url == end_url:
                        # we are done, we found the end!
                        return self._list_from_chain_(child_page)
                    else:
                        # aww... we need to keep looking
                        path_queue.put(child_page)

    def _list_from_chain_(self, page):
        """Follow the shortest path to get to the given page and
        convert it to a list of url strings"""
        lst = []
        cur = page
        while cur != null:
            lst.append(cur.url)
            cur = cur.path_to
        return lst

    def _get_page_children_(self, page):
        """Finds and returns a generator containing the pages (in mwclient form)"""
        p = self.site.Pages[page.url]
        return p.links()


